<template>
  <!-- 主要工序穿插技术 -->
  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules" :class="editModel == 0 ? '' : 'rulesForm'">
    <!-- 表格 -->
    <a-card :bordered="false">
      <title-name title="主要工序穿插技术"></title-name>
      <div>
        <a-button type="primary" @click="addLine" :disabled="editModel == 0">增行</a-button>
        <a-button @click="delLine" style="margin-left: 20px" :disabled="editModel == 0">删除行</a-button>
      </div>
      <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
        <template v-slot:table>
          <a-form-model-item class="formTable" label=" " :colon="false">
            <a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" ref="formTable" bordered :columns="columns" :data-source="form.list" :pagination="false">
              <template v-for="col in ['point', 'work', 'startTime', 'endTime','sort']" :slot="col" slot-scope="text, record,index">
                <div :key="col" class="form-item">
                  <template>
                    <template>
                      <BaseInput :maxLength='300' v-if="col === 'work' || col === 'point'" v-model="record[col]" :disabled="editModel == 0"></BaseInput>
                      <a-date-picker v-else-if="col === 'startTime'" value-format="YYYY-MM-DD" v-model="record[col]" :disabled="editModel == 0" @change="changeDate(index)"></a-date-picker>
                      <a-date-picker v-else-if="col === 'endTime'" value-format="YYYY-MM-DD" :disabled-date="(current)=>{return disabledDate(current,record)}" v-model="record[col]" :disabled="editModel == 0"></a-date-picker>
                      <span v-else>{{record[col]}}</span>
                    </template>
                  </template></div
              ></template>
            </a-table>
          </a-form-model-item>
        </template>
      </custom-form>
    </a-card>
  </a-form-model>
   
</template>

<script>
import { querySchemeMainProcessDetail,batchUpdateSchemeMainProcess} from '@/api/project/plannManagement/mainProcess.js' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import moment from 'moment'
import { isNull } from './model.js'
const columns = [
   {title: '序号',width: 80,dataIndex: 'sort',align: 'center'},
  { title: '主要工序穿插点', dataIndex: 'point', align: 'center', scopedSlots: { customRender: 'point' } },
  { title: '插入工作', dataIndex: 'work', align: 'center', scopedSlots: { customRender: 'work' } },
  { title: '计划开始时间', dataIndex: 'startTime', align: 'center', scopedSlots: { customRender: 'startTime' } },
  { title: '计划结束时间', dataIndex: 'endTime', align: 'center', scopedSlots: { customRender: 'endTime' } }
]
export default {
  name: 'mainProcess' + Date.now(),
  extends: new BaseEditPage(),
  components: {
  },
  props: {
    statusBasicSuc: {
      type: Boolean,
      default: () => {}
    }
  },
  data() {
    return {
      columns,
      editModel: 1, // 操作状态:0 查看;1 编辑
      planId: null,
      selectedRowKeys: [],
      status:null,
      form: {
        list: [
          {
            sort:1,
            point: null,
            work: null,
            startTime: null,
            endTime: null
          }
        ]
      }, // 表单
      id: '',
      rules: {}, // 校验规则
      init: false // 初始化控件
    }
  },
  watch: {
    statusBasicSuc: {
      handler(val, oldVal) {
        let form = this.$clone(this.form)
        form.status = this.status
        form.schemeDetailId = this.id
        form.changed = this.pageType == 'change' ? true : false // 是编辑还是变更
        val && this.statusBasicSucFn(form);
      },
      deep: true
    }
  },
  created() {},
  async mounted() {
    await this.getDetailData()
  },
  computed: {
    formList() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        }
      ]
    }
  },
  methods: {
    changeDate(index){
      let startTime = this.form.list[index].startTime,
      endTime = this.form.list[index].endTime;
      if(endTime && (new Date(startTime)>new Date(endTime))){
        this.form.list[index].endTime = null;
      }
    },
      disabledDate(current,row) {
      if (row.startTime) {
        let planStartTime;
        if (typeof row.startTime === 'string') {
          planStartTime = moment(row.startTime)
        } else {
          planStartTime = row.startTime
        }
        return current && current <= moment(planStartTime)
      }
      return true
    },  
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    //添加行
    addLine() {
      this.form.list.push({
        sort: this.form.list.length+1,
        point: null,
        work: null,
        startTime: null,
        endTime: null
      })
    },
    delLine() {
      let that = this
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择要删除的数据')
        return false
      }
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        title: '提示?',
        content: `请确认是否要删除?`,
        onOk() {
          that.sureDel()
        },
        onCancel() {}
      })
    },
    sureDel() {
      if (this.selectedRowKeys.length) {
        this.selectedRowKeys.map((item) => {
          delete this.form.list[item]
        })
      }
      this.selectedRowKeys = []
      let filterBlankArr = this.form.list.filter((item) => item) //过滤数组空白的数据
      this.form.list = filterBlankArr
    },
    getDetailData() {
      // 不为添加时请求详情
       this.$emit('update:spinning', true)
        let reqObj = {
          schemeDetailId: this.id,
          latestData:true
        }
        if (this.version) {
          reqObj.version = this.version,
          reqObj.latestData = false
        }
        querySchemeMainProcessDetail(reqObj)
          .then((res) => {
            this.$emit('update:spinning', false)
             if(res.data && res.data.length){
              this.form.list = res.data;
             }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
    },
    /**
     * 提交表单
     */
    mainProcessSubmit(baseData) {
      let dataDable = this.form.list
      if (!dataDable.length) {
        this.$message.warning('请至少填写一行数据')
        return
      } else {
        let rulesArr = []
        dataDable.map((item) => {
          let a = Object.values(item).every((oItem) => oItem)
          a && rulesArr.push(a)
        })
        let flag = rulesArr.length === dataDable.length
        if (!flag) {
          this.$message.warning('请完善表格数据')
          return
        }
      }
      this.sure(1, baseData)
    },
    sure(str, baseData) {
      let that = this
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交?`,
        onOk() {
          that.submitFn(str, baseData)
        },
        onCancel() {}
      })
    },
    mainProcessSaveDrafts(baseData) {
      //保存草稿
      this.submitFn(0, baseData)
    },
    submitFn(status, baseData) {
      this.$emit('update:spinning', true)
      baseData.schemeDetailId = this.id
      baseData.status = status
      this.status = status;
      this.$emit('updateBasicDetail', baseData)
    },
    statusBasicSucFn(formData){
        let msg = this.status * 1 === 1 ? '提交' : '保存草稿'
        let api = batchUpdateSchemeMainProcess
        api(formData).then(() => {
            this.$emit('update:spinning', false)
            this.$message.success(`${msg}成功！`)
             this.status * 1===1 && this.$multiTab.close()
        })
        .catch(() => {
          this.$message.warning(err.data.message)
          this.$emit('update:spinning', false)
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.scene {
  display: block;
  margin: 10px 0 10px 60px;
  color: rgba(0, 0, 0, 0.85);
}
.rulesForm {
  @{deep} .ant-input,
  @{deep} .ant-input-work-input,
  @{deep} .ant-select .ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  @{deep} .mandatory .ant-input {
    border-color: #d9d9d9;
    background-color: #fff;
  }
  @{deep} .setPlaceholder {
    .ant-select-selection__placeholder {
      display: block !important;
    }
  }
}
@{deep} .formTable {
  .ant-form-item-label {
    width: 0;
  }
  .ant-form-item-control-wrapper {
    width: 100%;
  }
}
</style>